import { createRouter, createWebHistory } from 'vue-router';

// 懒加载路由组件
const Login = () => import('../views/Login.vue');
const Home = () => import('../views/Home.vue');
const OrderList = () => import('../views/OrderList.vue');
const PrintRecords = () => import('../views/PrintRecords.vue');
const UserManagement = () => import('../views/UserManagement.vue');
const Profile = () => import('../views/Profile.vue');

// 路由配置
const routes = [
  { // 根路径不需要认证，因为子路由单独控制认证
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
    // 移除根路径的认证要求，避免与子路由认证冲突
    meta: { requiresAuth: true },
    children: [
      // 首页默认路由，直接渲染订单列表
      {
        path: '',
        name: 'HomeDefault',
        component: OrderList
      },
      {
        path: 'orders',
        name: 'OrderList',
        component: OrderList,
        meta: { requiresAuth: true }
      },
      {
        path: 'print-records',
        name: 'PrintRecords',
        component: PrintRecords,
        meta: { requiresAuth: true }
      },
      {
        path: 'users',
        name: 'UserManagement',
        component: UserManagement,
        meta: { requiresAuth: true }
      },
      { path: 'profile', name: 'Profile', component: Profile, meta: { requiresAuth: true, title: '个人中心' } }
    ]
  },
  // 重定向
  {
    path: '/:pathMatch(.*)*',
    redirect: '/login'
  }
];

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  // 获取本地存储的用户信息
  const user = localStorage.getItem('user');
  
  // 处理重定向到登录页的特殊情况，避免循环重定向
  if (to.path === '/login') {
    if (user) {
      // 已登录用户访问登录页，重定向到首页
      next({ path: '/orders' });
    } else {
      // 未登录用户可以访问登录页
      next();
    }
    return; // 避免继续执行后续逻辑
  }

  // 判断是否需要登录
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 需要登录但未登录
    if (!user) {
      next({ path: '/login' });
    } else {
      next();
    }
  } else {
    // 不需要登录的页面直接放行
    next();
  }
});

export default router;